package com.foreknow.demo14;

import java.sql.*;

/**
 * JDBC工具类
 */
public class DBUtil {
    Connection conn;
    PreparedStatement pstmt;
    ResultSet rs;

    /**
     * 连接数据库的方法
     *
     * @return
     */
    public Connection Connect() throws ClassNotFoundException, SQLException {
        //1.加载驱动 jdbc驱动类：5.7:com.mysql.jdbc.Driver  8.0:com.mysql.cj.jdbc.Driver
        Class.forName("com.mysql.jdbc.Driver");
        //2.获取连接
        conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/basic5?useUnicode=true&characterEncoding=utf8",
                "root", "root");
        return conn;
    }

    /**
     * 查询
     *
     * @return
     */
    public ResultSet Select(String sql, Object... values) throws SQLException {
        //3.获取prepareStatement对象用于执行动态SQL
        pstmt = conn.prepareStatement(sql);
        //将？替换具体的值
        for (int i = 0; i < values.length; i++) {
            pstmt.setObject(i + 1, values[i]);
        }
        rs = pstmt.executeQuery();
        return rs;

/*        List<GuestBook> list =null;
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs =
                    stmt.executeQuery("select * from guestbook");
            list= new ArrayList<>();
            while (rs.next()) {
                GuestBook gb = new GuestBook();
                gb.setId(rs.getInt("id"));
                gb.setName(rs.getString("name"));
                gb.setPhone(rs.getString("phone"));
                gb.setEmail(rs.getString("email"));
                gb.setTitle(rs.getString("title"));
                gb.setContent(rs.getString("content"));
                list.add(gb);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;*/
    }

    /**
     * DML(insert delete update)操作
     */
    public int Update(String sql, Object... values) throws SQLException {
        //3.获取prepareStatement对象用于执行动态SQL
        pstmt = conn.prepareStatement(sql);
        //将？替换具体的值
        for (int i = 0; i < values.length; i++) {
            pstmt.setObject(i + 1, values[i]);
        }
        int i = pstmt.executeUpdate();
        return i;
    }
    /**
     * 关闭资源
     */
    public void closed() throws SQLException {
        if (rs!=null){
            rs.close();
        }
        if (conn!=null){
            conn.close();
        }
        if (pstmt!=null){
            pstmt.close();
        }
    }
}
